package com.dhruvtaara.beta.toolset;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import com.dhruvtaara.beta.model.entities.Question;

public class QuestionParser {

	/**
	 * 
	 * @param questionsFile
	 * @return
	 * @throws ParserConfigurationException
	 * @throws IOException
	 * @throws SAXException
	 */
	public List<Question> Parse(InputStream questionStream)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(questionStream);

		document.getDocumentElement().normalize();

		Element root = document.getDocumentElement();

		NodeList questionNodes = root.getElementsByTagName("question");

		int totalQuestions = questionNodes.getLength();

		List<Question> questions = new ArrayList<Question>();

		for (int i = 0; i < totalQuestions; i++) {
			Element item = (Element) questionNodes.item(i);
			Question q = new Question();

			NodeList children = item.getChildNodes();

			q.setText(children.item(1).getTextContent());
			q.setSubject(item.getAttribute("subject"));

			NodeList choiceNodes = item.getElementsByTagName("choices").item(0)
					.getChildNodes();

			List<String> choices = new ArrayList<String>();
			for (int j = 0; j < choiceNodes.getLength(); j++) {
				Node n = choiceNodes.item(j);
				if (n.getNodeType() == 1) {
					choices.add(n.getTextContent());
				}
			}
			q.setChoices(choices);

			NodeList answerNodes = item.getElementsByTagName("answers").item(0)
					.getChildNodes();

			List<Integer> answers = new ArrayList<Integer>();
			for (int j = 0; j < answerNodes.getLength(); j++) {
				Node n = answerNodes.item(j);
				if (n.getNodeType() == 1) {
					answers.add(Integer.parseInt(n.getTextContent()));
				}
			}
			q.setAnswers(answers);

			questions.add(q);
		}

		return questions;
	}

}
